package com.originskyseed.platform.count.service.impl;

import java.math.BigDecimal;
import java.util.*;

import javax.annotation.Resource;

import com.originskyseed.platform.recruit.mapper.RecruitMapper;
import com.originskyseed.platform.user.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;

import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.tenant.util.TenantCodeUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.count.mapper.UserSalaryMapper;
import com.originskyseed.platform.count.model.UserSalary;
import com.originskyseed.platform.count.service.IUserSalaryService;
import com.originskyseed.platform.user.model.ParameterConfigure;

/**
 * 用户工资信息表Service接口实现类（OSI_USER_SALARY）
 * 
 * @author Tangwanghui
 */
@DubboService
@Component("userSalaryService")
public class UserSalaryServiceImpl implements IUserSalaryService {

	@Resource
	private UserSalaryMapper userSalaryMapper;

	@Resource
	private PlayerRelateRechargeMonthMapper playerRelateRechargeMonthMapper;

	@Resource
	private PlayerMapper playerMapper;

	@Resource
	private SalesmanLevelMapper salesmanLevelMapper;

	@Resource
	private RecruitMapper recruitMapper;

	/**
	 * 删除记录
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKey(String id) throws Exception {
		return this.userSalaryMapper.deleteByPrimaryKey(id);
	}

	/**
	 * 批量删除记录
	 * 
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKeys(List<String> ids) throws Exception {
		return this.userSalaryMapper.deleteByPrimaryKeys(ids);
	}

	/**
	 * 插入记录
	 * 
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insert(UserSalary record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.userSalaryMapper.insert(record);
	}

	/**
	 * 插入记录（仅非空值字段）
	 * 
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertSelective(UserSalary record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.userSalaryMapper.insertSelective(record);
	}

	/**
	 * 更新记录
	 * 
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKey(UserSalary record) throws Exception {
		record.setUpdateTime(new Date());
		return this.userSalaryMapper.updateByPrimaryKey(record);
	}

	/**
	 * 更新记录（仅非空值字段）
	 * 
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKeySelective(UserSalary record) throws Exception {
		record.setUpdateTime(new Date());
		return this.userSalaryMapper.updateByPrimaryKeySelective(record);
	}

	/**
	 * 查询记录
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public UserSalary selectByPrimaryKey(String id) throws Exception {
		return this.userSalaryMapper.selectByPrimaryKey(id);
	}

	/**
	 * 查询列表
	 * 
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<UserSalary> selectList(UserSalary record) throws Exception {
		return this.userSalaryMapper.selectList(record);
	}

	/**
	 * 分页查询列表
	 * 
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<UserSalary> selectListByPage(Map<String, Object> params, BasePage<UserSalary> page) throws Exception {
		params.put("page", page);
		List<UserSalary> list = this.userSalaryMapper.selectListByPage(params);
		page.setResults(list);
		return page;
	}

	/**
	 * 查询列表
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public List<UserSalary> selectListByMap(Map<String, Object> params) throws Exception{
		return this.userSalaryMapper.selectListByMap(params);
	}


	/**
	 * 根据日期新增工资结算数据
	 * 
	 * @param date
	 * @param tenantCode
	 * @return
	 * @throws Exception
	 */
	public int insertsUserSalaryByTime(String date, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}

		// 删除已存在的
		UserSalary query = new UserSalary();
		query.setMonth(date);
		List<UserSalary> userSalaries = this.userSalaryMapper.selectList(query);
		if (userSalaries.size() > 0) {
			List<String> list = new ArrayList<>();
			for (UserSalary  userSalary:userSalaries) {
				list.add(userSalary.getId());
			}
			this.userSalaryMapper.deleteByPrimaryKeys(list);
		}

		// 获取员工月度工资
		List<UserSalary> list = this.userSalaryMapper.selectUserSalaryByTime(date);
		for (UserSalary userSalary : list) {
			userSalary.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
			userSalary.setMonth(date);
			userSalary.setCreateTime(new Date());
			// 基本工资
			if (userSalary.getSalary() == null) {
				userSalary.setSalary(BigDecimal.ZERO);
			}
			// 有效奖金
			userSalary.setValidBonus(BigDecimal.ZERO);
			userSalary.setThreeTimesLogin(0);
			userSalary.setThreeTimesLoginBonus(BigDecimal.ZERO);
			userSalary.setSevenTimesLogin(0);
			userSalary.setSevenTimesLoginBonus(BigDecimal.ZERO);
			userSalary.setHighGradeBonus(BigDecimal.ZERO);
			// 优质奖金
			if (userSalary.getHighGradeCount() != null && userSalary.getQualityBonus() != null) {
				userSalary.setHighGradeBonus(new BigDecimal(userSalary.getHighGradeCount()).multiply(userSalary.getQualityBonus()));
			}
			userSalary.setNobleCount(0);
			userSalary.setNobleBonus(BigDecimal.ZERO);
			userSalary.setTiredFullCount(0);
			userSalary.setTiredFullBonus(BigDecimal.ZERO);
			userSalary.setTeamBonus(BigDecimal.ZERO);
			userSalary.setSum(BigDecimal.ZERO);

			//计算提成奖金
			if(StringUtils.isNotBlank(userSalary.getSalesmanLevelId()) && StringUtils.isNotBlank(userSalary.getOtherAccount())){
				// 获取新用户充值金额
				Map<String,Object> map = new HashMap<>();
				map.put("startTime",date+"-01 00:00:00");
				map.put("endTime",date+"-31 23:59:59");
				map.put("channelSubId",userSalary.getOtherAccount());

				// 获取新注册玩家id
				List<String> playerIdList = this.playerMapper.selectNewPlayerIdsByChannelSubId(map);
				if(playerIdList!=null && playerIdList.size()>0){
					map.put("list",playerIdList);
					BigDecimal amount = this.playerRelateRechargeMonthMapper.selectMonthNewRechargeAmountByOtherAccount(map);
					// 如果达到指定金额，则按当前等级的提成比例计算
					if(amount.compareTo(userSalary.getCommissionBase()) >= 0){
						userSalary.setTiredFullBonus(amount.multiply(userSalary.getCommissionRate()));

						// 如果没有达到金额，则查询下级的提成比较
					}else {
						BigDecimal commissionRate = this.salesmanLevelMapper.selectCommissionRateByAmount(amount);
						// 如果不满足，则查询最低级的提成比例
						if(commissionRate==null){
							commissionRate = this.salesmanLevelMapper.selectMinCommissionRateByAmount();
						}
						if(commissionRate!=null){
							userSalary.setTiredFullBonus(amount.multiply(commissionRate));
						}else {
							userSalary.setTiredFullBonus(BigDecimal.ZERO);
						}
					}
				}
			}else {
				userSalary.setTiredFullBonus(BigDecimal.ZERO);
			}

			// 计算内荐费用
			Map<String,Object> map = new HashMap<>();
			map.put("userId",userSalary.getUserId());
			map.put("startTime",date+"-01");
			map.put("endTime",date+"-31");
			BigDecimal nobleBonus =  this.recruitMapper.selectRecommendAmount(map);
			userSalary.setNobleBonus(nobleBonus);
		}

		int count = 0;
		// 一次性插入的数量
		int size = 500;
		// 总长度
		int length = list.size();
		// 计算可以分成多少组
		int num = (length + size - 1) / size;
		for (int i = 0; i < num; i++) {
			// 开始位置
			int fromIndex = i * size;
			// 结束位置
			int toIndex = (i + 1) * size < length ? (i + 1) * size : length;
			List<UserSalary> newUserSalaryList = list.subList(fromIndex, toIndex);
			count += userSalaryMapper.insertBatch(newUserSalaryList);
		}
		return count;
	}

}